package cn.lg.soar.message.mapper;

import cn.lg.soar.message.entity.Notice;
import cn.lg.soar.message.model.NoticeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public interface NoticeMapper extends BaseMapper<Notice> {

    /**
     * 分页查询用户消息
     * @param page
     * @param userId
     * @param queryWrapper
     * @return
     */
    @Select("SELECT * FROM ( " +
            " SELECT a.*, b.`status` FROM lg_msg_notice a  " +
            " INNER JOIN lg_msg_notice_recipient b ON a.id=b.notice_id AND b.user_id=#{userId} AND b.`status` IN(0, 1) " +
            " UNION ALL " +
            " SELECT a.*, 0 as 'b.status' FROM lg_msg_notice a  " +
            " WHERE " +
            " a.recipient_type=0 " +
            " AND not exists(SELECT 1 FROM lg_msg_notice_recipient b WHERE b.notice_id=a.id AND b.user_id=#{userId}) " +
            ") t ${ew.customSqlSegment}")
    IPage<NoticeVo> page(IPage<NoticeVo> page, @Param("userId") Long userId, @Param(Constants.WRAPPER) QueryWrapper<NoticeVo> queryWrapper);

    /**
     * 统计用户消息数量
     * @param userId
     * @param queryWrapper
     * @return
     */
    @Select("SELECT COUNT(*) FROM ( " +
            " SELECT 1 FROM lg_msg_notice a  " +
            " INNER JOIN lg_msg_notice_recipient b ON a.id=b.notice_id AND b.user_id=#{userId} AND b.`status` IN(0, 1) " +
            " UNION ALL " +
            " SELECT 1 FROM lg_msg_notice a  " +
            " WHERE " +
            " a.recipient_type=0 " +
            " AND not exists(SELECT 1 FROM lg_msg_notice_recipient b WHERE b.notice_id=a.id AND b.user_id=#{userId}) " +
            ") t ${ew.customSqlSegment}")
    long count(@Param("userId") Long userId, @Param(Constants.WRAPPER) QueryWrapper<NoticeVo> queryWrapper);

}
